package fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.administrator.boltshow.BrandDetailActivity;
import com.example.administrator.boltshow.LoginActivity;
import com.example.administrator.boltshow.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import adapter.AllPraiseAdapter;
import application.MyApplication;
import config.NetConfig;
import decoration.ItemDecoration;
import model.AllPraiseModel;
import model.UserCollect;

/**
 * Created by lenovo on 2016/8/29.
 */
public class AllPraiseFragment extends Fragment {
    private TextView mEmpty;
    private RecyclerView mRecyclerView;
    private ImageView imageView;
    private AllPraiseAdapter mAdapter;
    private List<AllPraiseModel.BrandsBean> mData;
    private GridLayoutManager manager;
    private int CurrentPage = 1;
    private CheckBox mRbClassify, mRbOrder, mRbSelect;
    private View mSelectContentView, mOrderContentView, mClassifyContentView;
    private PopupWindow mPopupWindow;
    private RadioGroup mClassifyRadioGroup, mOrderRadioGroup, mSelectRadioGroup;
    private int catId = 0, brandType = 0, sortType = 0;
    private DbManager mDb;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.allpraise, null);
        initView(view);
        initData();

        setListener();
        setData();
        return view;


    }



    private void setListener() {
        //加载筛选的布局
        mSelectContentView = LayoutInflater.from(getContext()).inflate(
                R.layout.allpraise_pop_window_select, null);
        //加载分类的布局
        mClassifyContentView = LayoutInflater.from(getContext()).inflate(
                R.layout.allpraise_pop_window, null);
        //加载排序的布局
        mOrderContentView = LayoutInflater.from(getContext()).inflate(
                R.layout.allpraise_pop_window_order, null);

        //分类事件的监听
        mRbClassify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            private Drawable drawable;

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {

                    drawable = getResources().getDrawable(R.mipmap.collection_up);

                    showPopupWindow(buttonView, mClassifyContentView);
                    mClassifyRadioGroup = (RadioGroup) mClassifyContentView.findViewById(R.id.rg_pop_classify);
                    mClassifyRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                          RadioButton radioButton = (RadioButton) mClassifyContentView.findViewById(mClassifyRadioGroup.getCheckedRadioButtonId());
                            int id = radioButton.getId();
                            switch (id) {
                                case R.id.tv_pop_all:
                                    catId = 0;
                                    break;
                                case R.id.tv_pop_sport:
                                    catId = 1;
                                    break;
                                case R.id.tv_pop_cloths:
                                    catId = 2;
                                    break;
                                case R.id.tv_pop_beauty:
                                    catId = 3;
                                    break;
                                case R.id.tv_pop_more:
                                    catId = 4;
                                    break;
                                case R.id.tv_pop_shoes:
                                    catId = 5;
                                    break;
                            }

                            Log.i("TAG", "++++sortType" + sortType+","+brandType+","+catId);

                            CharSequence text = radioButton.getText();
                            mRbClassify.setText(text);
                            loadMore(CurrentPage);
                            //Todo开启一个动画 在动画结束的时候， mPopupWindow.dismiss();
                            //   mSelectRadioGroup.startAnimation();
                            radioButton.setChecked(true);
                            mPopupWindow.dismiss();


                        }
                    });

                } else {

                    drawable = getResources().getDrawable(R.mipmap.collection_down);

                }
                if (drawable != null) {

                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mRbClassify.setCompoundDrawables(null, null, drawable, null);
                }
            }
        });
        //排序事件的监听
        mRbOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            private Drawable drawable;

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    drawable = getResources().getDrawable(R.mipmap.collection_up);


                    showPopupWindow(buttonView, mOrderContentView);
                    mOrderRadioGroup = (RadioGroup) mOrderContentView.findViewById(R.id.rg_pop_order);
                    mOrderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            RadioButton radioButton = (RadioButton) mOrderContentView.findViewById(mOrderRadioGroup.getCheckedRadioButtonId());
                            int id = radioButton.getId();
                            switch (id) {
                                case R.id.tv_order_moren:
                                    sortType = 0;
                                    break;
                                case R.id.tv_order_current:
                                    sortType = 1;
                                    break;
                                case R.id.tv_order_three:
                                    sortType = 2;
                                    break;
                                case R.id.tv_order_four:
                                    sortType = 3;
                                    break;

                            }


                            CharSequence text = radioButton.getText();
                            mRbOrder.setText(text);
                            loadMore(CurrentPage);
                            //Todo开启一个动画 在动画结束的时候， mPopupWindow.dismiss();
                            //   mSelectRadioGroup.startAnimation();
                            radioButton.setChecked(true);
                            mPopupWindow.dismiss();


                        }
                    });
                } else {
                    drawable = getResources().getDrawable(R.mipmap.collection_down);
                }
                if (drawable != null) {
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mRbOrder.setCompoundDrawables(null, null, drawable, null);
                }
            }
        });
        //筛选事件的监听
        mRbSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            private Drawable drawable;

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    drawable = getResources().getDrawable(R.mipmap.collection_up);


                    showPopupWindow(buttonView, mSelectContentView);
                    mSelectRadioGroup = (RadioGroup) mSelectContentView.findViewById(R.id.rg_pop_select);
                    mSelectRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            RadioButton radioButton = (RadioButton) mSelectContentView.findViewById(mSelectRadioGroup.getCheckedRadioButtonId());
                            int id = radioButton.getId();
                            switch (id) {
                                case R.id.tv_select_one:
                                    brandType = 0;
                                    break;
                                case R.id.tv_select_two:
                                    brandType = 1;
                                    break;
                                case R.id.tv_select_three:
                                    brandType = 2;
                                    break;
                                case R.id.tv_select_four:
                                    brandType = 3;
                                    break;
                                case R.id.tv_select_five:
                                    brandType = 4;
                                    break;


                            }


                            CharSequence text = radioButton.getText();
                            mRbSelect.setText(text);
                            //Todo开启一个动画 在动画结束的时候， mPopupWindow.dismiss();
                            //   mSelectRadioGroup.startAnimation();
                            loadMore(CurrentPage);
                            radioButton.setChecked(true);
                            mPopupWindow.dismiss();


                        }
                    });

                    if (!mPopupWindow.isShowing()) {
                        mRbSelect.setChecked(false);

                    }

                } else {
                    drawable = getResources().getDrawable(R.mipmap.collection_down);
                }
                if (drawable != null) {
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mRbSelect.setCompoundDrawables(null, null, drawable, null);

                }
            }
        });
       mAdapter.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               MyApplication myApplication= (MyApplication) getActivity().getApplication();
               boolean isLogin = myApplication.getIsLogin();
               if(isLogin) {
                   String userName = myApplication.getUserName();
                   UserCollect userCollect=new UserCollect();
                   userCollect.setName(userName);
                   Integer position= (Integer) v.getTag();
                   userCollect.setBrandId(mData.get(position).getBrandId());
                   try {
                       mDb.save(userCollect);
                   } catch (DbException e) {
                       e.printStackTrace();
                   }


               }else {
                   Intent intent=new Intent(getActivity(), LoginActivity.class);
                   getActivity().startActivity(intent);
               }
           }
       });

    }

    private void setData() {
        manager = new GridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Integer position = (Integer) v.getTag();
                final String brandId = mData.get(position).getBrandId();
                final String brandName = mData.get(position).getBrandName();

                Intent intent = new Intent(getActivity(), BrandDetailActivity.class);
                intent.putExtra("brandId", brandId);
                intent.putExtra("brandName", brandName);
                getActivity().startActivity(intent);
            }
        });
    }



    private void initView(View view) {
        DbManager.DaoConfig config = new DbManager.DaoConfig();
        mDb=x.getDb(config);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.prv_praise_show);
        mRecyclerView.addItemDecoration(new ItemDecoration(2));
        mRbClassify = (CheckBox) view.findViewById(R.id.tv_allpraise_classify);
        mRbOrder = (CheckBox) view.findViewById(R.id.tv_allpraise_order);
        mRbSelect = (CheckBox) view.findViewById(R.id.tv_allpraise_select);
        mEmpty= (TextView) view.findViewById(R.id.tv_allPraise_empty);
    }

    private void initData() {
        mData = new ArrayList<>();
        mAdapter = new AllPraiseAdapter(getActivity(), mData);
        loadMore(1);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int itemPosition = manager.findLastVisibleItemPosition();

                    if (itemPosition == mData.size() - 1) {
                        CurrentPage++;
                        loadMore(CurrentPage);
                    }
                }
            }
        });

    }

    private void loadMore(int currentPage) {
        Log.i("Test", "catId,brandType,sortType"+catId+brandType+sortType);
        Log.i("xxx", "jinlaila");
        // TODO: 2016/8/31
        String format = String.format(NetConfig.PRICE_PATH,catId,brandType,sortType, currentPage);
        x.http().get(new RequestParams(format), new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Log.i("xxx", "result"+result);
                if (result != null) {
                    Log.i("xxx", "xxx");
                    Gson gson = new Gson();
                    AllPraiseModel allPraiseModel = gson.fromJson(result, AllPraiseModel.class);
                    List<AllPraiseModel.BrandsBean> brands = allPraiseModel.getBrands();
                    if(brands==null) {
                        mData.clear();
                        mAdapter.notifyDataSetChanged();
                        mEmpty.setVisibility(View.VISIBLE);
                        return;
                    }
                    mData.clear();
                    mData.addAll(brands);
                    mEmpty.setVisibility(View.INVISIBLE);
                    Log.i("xxx", "mData"+mData.size());
                    String title = allPraiseModel.getTitle();
                    imageView = new ImageView(getActivity());
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Picasso.with(getActivity()).load(title).into(imageView);
                    mAdapter.notifyDataSetChanged();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("xxx", "chucuo");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    public void showPopupWindow(View view, View mContentView) {


        mPopupWindow = new PopupWindow(mContentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        //  mPopupWindow.setAnimationStyle(R.style.Animation_ZoomLight);
        //  WindowManager.LayoutParams params=getActivity().getWindow().getAttributes();
        //   params.alpha=0.7f;

        // getActivity().getWindow().setAttributes(params);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mRbSelect.setChecked(false);
                mRbClassify.setChecked(false);
                mRbOrder.setChecked(false);

                return false;

            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.white));
        mPopupWindow.setAnimationStyle(R.style.MypopWindow);
        // 设置好参数之后再show
        mPopupWindow.showAsDropDown(view);

    }


}
